$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


var _common = {
    request: function(param) {
        var _this = this;
        $.ajax({
            url: param.url || '',
            type: param.method || 'get',
            dataType: param.type || 'json',
            contentType: "application/json; charset=utf-8",
            data: param.data || '',
            success: function(res) {
                // 状态 status + 数据 data

                // 请求数据正确，调用param.success方法
                if (res.status === "1") {
                    typeof param.success === 'function' && param.success(res.data, res.message);
                }
                // 未登录
                else if (res.status === "3") {
                    alert('未登录');
                }
                // 请求数据错误, 调用param.error方法
                else if (res.status === "2") {
                    typeof param.error === 'function' && param.error(res.message);
                }
            },
            error: function(err) {
                // 404 503
                typeof param.error === 'function' && param.error(err.statusText);
            }
        });
    }
}

// 新增角色
var request_role_new = function(data, resolve, reject) {
    _common.request({
        url: '/a/wxconf/productType',
        method: 'PUT',
        data: data,
        success: resolve,
        error: reject
    })
};
// 删除角色
var request_role_del = function(data, resolve, reject) {
    _common.request({
        url: '/a/wxconf/productType',
        method: 'delete',
        data: data,
        success: resolve,
        error: reject
    })
};
// 获取角色
var request_role_get = function(id, resolve, reject) {
    _common.request({
        url: '/a/wxconf/productType',
        method: 'get',
        data: "id=" + id,
        success: resolve,
        error: reject
    })
};

var roleManage = function() {

    var _init = function() {

        var table = $('#table_role');

        table.dataTable({
            "processing": true,
            // 开启服务器模式
            serverSide: true,
            "ajax": {
                url: "/a/wxconf/productTypes", // 列表查询
                // data: json
            },
            "autoWidth": false,
            "columns": [{
                    "width": "10%",
                    "data": "null",
                    "defaultContent": "<label class=\"mt-checkbox mt-checkbox-single mt-checkbox-outline\"><input type=\"checkbox\" class=\"checkboxes\" value=\"1\"><span></span></label>"
                },
                {
                    "width": "35%",
                    "data": "name"
                },
                {
                    "width": "35%",
                    "data": "createDate"
                },
                {
                    "width": "30%",
                    "data": "null",
                    "defaultContent": "<button type=\"button\" class=\"btn blue btn_edit_role\">修改</button><button type=\"button\" class=\"btn red btn_del_role\">删除</button>"
                }
            ],
            "language": {
                "lengthMenu": "每页显示 _MENU_ 条记录",
                "emptyTable": "暂无数据记录",
                "info": "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
                "zeroRecords": "没有搜索到匹配记录",
                "infoEmpty": "",
                "infoFiltered": "",
                "processing": "数据加载中,请稍后..."
            },
            "pageLength": 5,
            "order": [
                [2, "asc"]
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0, 3]
            }, {
                "targets": 2,
                "render": function(data, type, row, meta) {
                    console.log(data);
                    return data;
                }
            }],
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'row'<'col-md-5'i><'col-md-7'>p>",
            "fnInitComplete": function() {}
        });

        // 选择列表
        // table.find('.group-checkable').change(function() {
        //     var set = $(this).attr("data-set");
        //     var checked = $(this).is(":checked");
        //     $(set).each(function() {
        //         if (checked) {
        //             $(this).prop("checked", true);
        //             $(this).parents('tr').addClass("active");
        //         } else {
        //             $(this).prop("checked", false);
        //             $(this).parents('tr').removeClass("active");
        //         }
        //     });
        // });
        // table.on('change', 'tbody tr .checkboxes', function() {
        //     $(this).parents('tr').toggleClass("active");
        // });

        // 关闭弹框
        $(".modal").on('hidden.bs.modal', function(e) {
            $('.modal .help-block').html(''); // 清空提示
            $('.modal input').val(''); // 清空 input
        });
        // 添加
        $('#btn_new_role').click(function(event) {
            $('#modal_new_role').modal('show');
        });

        // 修改
        table.on('click', '.btn_edit_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象

            var _id = oData_arr[0].id;
            var _name = oData_arr[0].name;

            $('#modal_edit_role').find('input[type=hidden]').val(_id);
            $('#modal_edit_role [name="name"]').val(_name);

            request_role_get(_id, function(res) {
                // 正确
                console.log(res);
            }, function(err) {
                //	错误
                alert(err);
            })

            $('#modal_edit_role').modal('show');
        });

        // 删除
        table.on('click', '.btn_del_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            alert(_id);
            bootbox.dialog({
                message: "确定要删除",
                title: "提示",
                buttons: {
                    cancel: {
                        label: "取消",
                        className: "btn dark btn-outline"
                    },
                    success: {
                        label: "确定",
                        className: "btn green",
                        callback: function() {
                            // alert('提交删除');
                            var _data = JSON.stringify({ id: _id });
                            request_role_del(_data, function(res) {
                                // 正确
                                table.DataTable().ajax.reload();
                            }, function(err) {
                                //	错误
                                alert(err);
                            })
                        }
                    }
                }
            });
        });
    }

    return {
        init: function() {
            _init();
        }

    };

}();

var roleForm = function() {

    // 新建表单验证
    var validate_role_new = function() {

        var form_new = $('#form_role_new');
        var error_new = $('.alert-danger', form_new);
        var success_new = $('.alert-success', form_new);
        var server_error_new = $('.alert-warning', form_new);

        form_new.validate({
            errorElement: 'span',
            errorClass: 'help-block help-block-error',
            focusInvalid: false,
            ignore: "", // 不验证隐藏input
            rules: {
                name: {
                    required: true
                },
                relaIds: {
                    required: true
                }
            },
            messages: {
                name: {
                    required: "请填写商品分类"
                },
                relaIds: {
                    required: "请选择商品分类"
                }
            },

            errorPlacement: function(error, element) {
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element);
                }
            },

            invalidHandler: function(event, validator) {
                success_new.hide();
                server_error_new.hide();
                error_new.show();
            },

            highlight: function(element) {
                $(element)
                    .closest('.form-group').addClass('has-error');
            },

            unhighlight: function(element) {
                $(element)
                    .closest('.form-group').removeClass('has-error');
            },

            success: function(label) {
                label
                    .closest('.form-group').removeClass('has-error');
            },

            submitHandler: function(form) {
                success_new.show();
                error_new.hide();
                server_error_new.hide();
                $(form).find('button[type=submit]').attr('disabled', 'disabled');

                var _data = JSON.stringify($(form).serializeObject());

                request_role_new(_data, function(res) {
                    // 正确
                    $("#table_role").DataTable().ajax.reload(); // 刷新table
                    $('#modal_new_role').modal('hide');
                }, function(err) {
                    //	错误
                    success_new.hide();
                    server_error_new.show();
                    server_error_new.html(err);
                    $(form).find('button[type=submit]').removeAttr('disabled');
                })

                return false;
            }
        });
    }

    // 编辑表单验证
    var validate_role_edit = function() {

        var form_edit = $('#form_role_edit');
        var error_edit = $('.alert-danger', form_edit);
        var success_edit = $('.alert-success', form_edit);
        var server_error_edit = $('.alert-warning', form_edit);

        form_edit.validate({
            errorElement: 'span',
            errorClass: 'help-block help-block-error',
            focusInvalid: false,
            ignore: "", // 不验证隐藏input
            rules: {
                name: {
                    required: true
                },
                relaIds: {
                    required: true
                }
            },
            messages: {
                name: {
                    required: "请填写菜单分类名称"
                },
                relaIds: {
                    required: "请选择菜单分类"
                }
            },

            errorPlacement: function(error, element) {
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element);
                }
            },

            invalidHandler: function(event, validator) {
                success_edit.hide();
                server_error_edit.hide();
                error_edit.show();
            },

            highlight: function(element) {
                $(element)
                    .closest('.form-group').addClass('has-error');
            },

            unhighlight: function(element) {
                $(element)
                    .closest('.form-group').removeClass('has-error');
            },

            success: function(label) {
                label
                    .closest('.form-group').removeClass('has-error');
            },

            submitHandler: function(form) {
                success_edit.show();
                error_edit.hide();
                server_error_edit.hide();
                $(form).find('button[type=submit]').attr('disabled', 'disabled');
                $.ajax({
                        url: '/a/wxconf/productType',
                      //  type: $(form).attr('method'),
                        type:'POST',
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify($(form).serializeObject())
                    })
                    .done(function(data) {

                        if (data.status === '1') {
                            // 正确
                            $("#table_role").DataTable().ajax.reload(); // 刷新table
                            $('#modal_edit_role').modal('hide');
                        } else if (data.status === '2') {
                            // 错误
                            success_edit.hide();
                            server_error_edit.show();
                            server_error_edit.html(data.info);
                            $(form).find('button[type=submit]').removeAttr('disabled'); // 返回错误信息
                        }

                    })
                    .fail(function() {
                        console.log("error");
                    });

                return false;
            }
        });
    }

    return {
        init: function() {
         //   validate_role_new();
          //  validate_role_edit();
        }

    };
}();

$(function() {
    roleManage.init();
    roleForm.init();
});